#!/usr/bin/env python3
"""
Command Line Interface for GSI Wiki Generator
"""

import argparse
import sys
from pathlib import Path

from .config import WikiConfig, create_config_template
from .generator import GSIWikiGenerator


def main():
    """Main CLI entry point"""
    parser = argparse.ArgumentParser(
        description="GSI DRP-4DVar Wiki Generator with Codebase-RAG Integration",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Generate wiki for comGSI-wiki directory
  gsi-wiki-gen --input-dir /path/to/comGSI-wiki --output-dir ./output
  
  # Check progress
  gsi-wiki-gen --progress
  
  # Reset cache
  gsi-wiki-gen --reset
  
  # Create configuration template
  gsi-wiki-gen --create-config config.json
        """
    )
    
    parser.add_argument(
        '--input-dir', '-i',
        type=str,
        default="/home/docker/comgsi/tutorial/comGSIv3.7_EnKFv1.3/src/comGSI-wiki",
        help='Input directory containing GSI codebase (default: comGSI-wiki)'
    )
    
    parser.add_argument(
        '--output-dir', '-o',
        type=str,
        default="./gsi_wiki_output",
        help='Output directory for generated files (default: ./gsi_wiki_output)'
    )
    
    parser.add_argument(
        '--config', '-c',
        type=str,
        help='Configuration file path (JSON format)'
    )
    
    parser.add_argument(
        '--outline-file',
        type=str,
        default="gsi_drp4dvar_wiki_outline.json",
        help='Wiki outline file name (default: gsi_drp4dvar_wiki_outline.json)'
    )
    
    parser.add_argument(
        '--max-results',
        type=int,
        default=10,
        help='Maximum search results per query (default: 10)'
    )
    
    parser.add_argument(
        '--min-score',
        type=float,
        default=0.2,
        help='Minimum similarity score for search results (default: 0.2)'
    )
    
    parser.add_argument(
        '--progress',
        action='store_true',
        help='Check current progress and exit'
    )
    
    parser.add_argument(
        '--reset',
        action='store_true',
        help='Reset progress cache and exit'
    )
    
    parser.add_argument(
        '--create-config',
        type=str,
        metavar='FILE',
        help='Create configuration template file and exit'
    )
    
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='Enable verbose logging'
    )
    
    args = parser.parse_args()
    
    try:
        # Handle special commands
        if args.create_config:
            create_config_template(args.create_config)
            print(f"✅ Configuration template created: {args.create_config}")
            return 0
        
        # Load configuration
        if args.config:
            config = WikiConfig.from_file(args.config)
        else:
            config = WikiConfig()
        
        # Override config with command line arguments
        config.input_directory = args.input_dir
        config.output_directory = args.output_dir
        config.outline_file = args.outline_file
        config.max_results = args.max_results
        config.min_score = args.min_score
        
        # Initialize generator
        generator = GSIWikiGenerator(config)
        
        # Handle progress check
        if args.progress:
            progress = generator.get_progress_report()
            print(f"""
📊 === GSI Wiki Generator Progress Report ===

🔍 搜索进度:
   完成: {progress['completed_searches']}/{progress['total_searches']} ({progress['search_progress_percent']:.1f}%)
   剩余: {progress['remaining_searches']} 个搜索

❓ 问题解答进度:
   完成: {progress['completed_questions']}/{progress['total_questions']} ({progress['question_progress_percent']:.1f}%)
   剩余: {progress['remaining_questions']} 个问题

📁 目录设置:
   输入目录: {progress['input_directory']}
   输出目录: {config.output_directory}

📅 会话信息:
   会话ID: {progress['session_id']}
   最后更新: {progress['last_updated'] or '尚未开始'}
            """)
            return 0
        
        # Handle reset
        if args.reset:
            print("🔄 Resetting progress cache...")
            generator.reset_progress_cache()
            print("✅ Progress cache has been reset")
            return 0
        
        # Normal wiki generation
        print("🚀 Starting GSI Wiki Generator")
        print(f"📁 Input directory: {config.input_directory}")
        print(f"📁 Output directory: {config.output_directory}")
        
        # Show current progress if resuming
        progress = generator.get_progress_report()
        if progress['completed_questions'] > 0 or progress['completed_searches'] > 0:
            print(f"📊 Resuming from cache - Searches: {progress['completed_searches']}/{progress['total_searches']}, Questions: {progress['completed_questions']}/{progress['total_questions']}")
        
        # Generate wiki
        wiki_file = generator.save_wiki()
        
        print(f"""
🎉 === Wiki Generation Completed ===

✅ Wiki document: {wiki_file}
✅ Output directory: {config.output_directory}

📊 Final statistics:
   搜索完成: {generator.get_progress_report()['completed_searches']} 个
   问题解答: {generator.get_progress_report()['completed_questions']} 个
   
🚀 Ready for use!
        """)
        
        return 0
        
    except KeyboardInterrupt:
        print("\n⚠️  Generation interrupted by user")
        print("💡 Progress has been saved. You can resume with the same command.")
        return 1
    except Exception as e:
        print(f"❌ Error during wiki generation: {str(e)}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        return 1


def show_help():
    """Show help information"""
    print("""
🚀 GSI DRP-4DVar Wiki Generator

A professional software package for generating comprehensive GSI DRP-4DVar 
implementation wikis using codebase-rag search and Claude AI integration.

Features:
- 🔍 Intelligent codebase search using codebase-rag
- 🤖 AI-powered technical answers via Claude
- 📦 Smart caching with resume capability
- 📁 Clean organized output structure
- 🚀 Production-ready logging and error handling

Quick Start:
  gsi-wiki-gen --input-dir /path/to/comGSI-wiki --output-dir ./output

For full help:
  gsi-wiki-gen --help
    """)


if __name__ == "__main__":
    sys.exit(main())